package com.micro.config.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtils {

    private static final String secret = "test123456";

    /**
     * @Author HJJ
     * @Date 2022-12-28 16:59
     * @Params  userId，userName
     * @Return token
     * @Description 创建Token，默认时间为7天
     */
    public static String createToken(String userName, String authentications){
        long expire = 7 * 24 * 3600 * 1000;
        return JWT.create().withAudience(userName)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis()+ expire))
                .withClaim("authentications", authentications)
                .sign(Algorithm.HMAC256(userName+secret));
    }

    /**
     * @Author HJJ
     * @Date 2022-12-28 16:59
     * @Params token, userName
     * @Return boolean
     * @Description 验证Token，过期或不正确时会返回false
     */
    public static boolean verifyToken(String token, String userName){
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(userName+secret)).build();
            jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            System.out.println(e);
        }
        return false;
    }

}
